<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Java高级-常用类-String、Date、Compare、Other | 恒星同学</title><meta name="keywords" content="Java"><meta name="author" content="hengxingstu"><meta name="copyright" content="hengxingstu"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="本篇讲解java常用类 String类String:字符串，使用一对””引起来表示。  String类被声明为final的，不可被继承。  String实现了Serializable接口：表示字符串是支持序列化的。 ​         实现了Comparable接口：表示String可以比较大小  String内部定义了final char[] value用于存储字符串数据  String:代表">
<meta property="og:type" content="article">
<meta property="og:title" content="Java高级-常用类-String、Date、Compare、Other">
<meta property="og:url" content="https://hengxingstu.gitee.io/2023/02/03/code/Java%E5%B8%B8%E7%94%A8%E7%B1%BB/index.html">
<meta property="og:site_name" content="恒星同学">
<meta property="og:description" content="本篇讲解java常用类 String类String:字符串，使用一对””引起来表示。  String类被声明为final的，不可被继承。  String实现了Serializable接口：表示字符串是支持序列化的。 ​         实现了Comparable接口：表示String可以比较大小  String内部定义了final char[] value用于存储字符串数据  String:代表">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s2.loli.net/2023/02/03/uwhRQAO6rqZgWVi.jpg">
<meta property="article:published_time" content="2023-02-03T03:55:00.000Z">
<meta property="article:modified_time" content="2023-02-08T03:00:21.815Z">
<meta property="article:author" content="hengxingstu">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s2.loli.net/2023/02/03/uwhRQAO6rqZgWVi.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://hengxingstu.gitee.io/2023/02/03/code/Java%E5%B8%B8%E7%94%A8%E7%B1%BB/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java高级-常用类-String、Date、Compare、Other',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-02-08 11:00:21'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.1.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://wallpapercave.com/uwp/uwp2365506.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">36</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fa-fw fas fa-comment-dots"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://s2.loli.net/2023/01/31/TyPcrql46CJWB8D.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">恒星同学</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 娱乐</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fa-fw fas fa-comment-dots"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java高级-常用类-String、Date、Compare、Other</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-02-03T03:55:00.000Z" title="发表于 2023-02-03 11:55:00">2023-02-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-02-08T03:00:21.815Z" title="更新于 2023-02-08 11:00:21">2023-02-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java高级-常用类-String、Date、Compare、Other"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2023/02/03/code/Java%E5%B8%B8%E7%94%A8%E7%B1%BB/#post-comment"><span id="twikoo-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><img src="https://s2.loli.net/2023/02/03/uwhRQAO6rqZgWVi.jpg" alt="5cb056d96f727"></p>
<p>本篇讲解java常用类</p>
<h1 id="String类"><a href="#String类" class="headerlink" title="String类"></a>String类</h1><p>String:字符串，使用一对””引起来表示。</p>
<ol>
<li><p>String类被声明为final的，不可被继承。</p>
</li>
<li><p>String实现了<code>Serializable</code>接口：表示字符串是支持序列化的。</p>
<p>​         实现了<code>Comparable</code>接口：表示String可以比较大小</p>
</li>
<li><p>String内部定义了<code>final char[] value</code>用于存储字符串数据</p>
</li>
<li><p>String:代表不可变的字符序列。简称：不可变性。</p>
<p>体现：</p>
<ul>
<li>当对字符串重新赋值时，需要重新指定内存区域赋值，不能使用原有的value进行赋值。</li>
<li>当对现有的字符串进行连接操作时，同上。</li>
<li>当调用String的<code>replace()</code>方法修改指定字符或字符串时，同上。</li>
</ul>
</li>
<li><p>通过字面量的方式（区别于new）给一个字符串赋值，此时的字符串值声明在字符串常量池中。</p>
</li>
<li><p>字符串常量池中是不会存储相同内容的字符串的。</p>
</li>
</ol>
<p>String的实例化方式：</p>
<p>方式一：通过字面量定义的方式，如下图左</p>
<p>方式二：通过new + 构造器的方式，如下图右</p>
<p><img src="https://s2.loli.net/2023/02/03/Tf2BtRySPcNxZUh.png" alt="String的实例化方式对比"></p>
<blockquote>
<p>面试题：String s &#x3D; new String(“abc”);方式创建对象，在内存中创建了几个对象？</p>
<p>答：两个:一个是堆空间中new结构，另一个是<code>char[]</code>对应的常量池中的数据：”abc”</p>
</blockquote>
<h2 id="字符串拼接"><a href="#字符串拼接" class="headerlink" title="字符串拼接"></a>字符串拼接</h2><ol>
<li>常量与常量的拼接结果在常量池。 且常量池中不会存在相同内容的常量。</li>
<li>只要其中有一个是变量， 结果就在堆中，相当于new出来的对象对象中有一个value指向常量池的地址</li>
<li>如果拼接的结果调用<code>intern()</code>方法， 返回值就是常量池的地址</li>
</ol>
<img src="https://s2.loli.net/2023/02/03/RLt5rxAZ3H9NYXb.png" alt="image-20230203155553307" style="zoom:50%;" />

<h3 id="面试题"><a href="#面试题" class="headerlink" title="面试题"></a>面试题</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">StringTest</span> <span class="token punctuation">&#123;</span>

    <span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token string">"good"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> ch <span class="token operator">=</span> <span class="token punctuation">&#123;</span> <span class="token char">'t'</span><span class="token punctuation">,</span> <span class="token char">'e'</span><span class="token punctuation">,</span> <span class="token char">'s'</span><span class="token punctuation">,</span> <span class="token char">'t'</span> <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">change</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token keyword">char</span> ch<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        str <span class="token operator">=</span> <span class="token string">"test ok"</span><span class="token punctuation">;</span>
        ch<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token char">'b'</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">StringTest</span> ex <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringTest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        ex<span class="token punctuation">.</span><span class="token function">change</span><span class="token punctuation">(</span>ex<span class="token punctuation">.</span>str<span class="token punctuation">,</span> ex<span class="token punctuation">.</span>ch<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>ex<span class="token punctuation">.</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//good</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>ex<span class="token punctuation">.</span>ch<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//best</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>首先，初始化str和ch时的内存模型为：</p>
<img src="https://s2.loli.net/2023/02/03/ByhQImlqoidscuL.png" alt="image-20230203162706600" style="zoom:33%;" />

<p>进入<code>change()</code>方法后：</p>
<p>声明了一个形参str，形参传入的是地址，相当于直接指向value。ch则是数组，直接指向数组地址。</p>
<p>str通过字面量赋值修改，由于String值的不可变性，直接在常量池中重新开辟空间赋值。现在，两个str就有区别了，一个是change方法中的str，一个是ex对象中的str属性，它们分别指向不同的地址。</p>
<p>ch也进行了修改，数组可以进行直接修改，所以test被修改为了best。</p>
<img src="https://s2.loli.net/2023/02/03/erLJtjcRyEhf3QA.png" alt="image-20230203163507479" style="zoom:33%;" />

<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><p>为了进一步说明字符串的常量与变量间的区别，我们有下面的例子</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"hellojava"</span><span class="token punctuation">;</span>
<span class="token keyword">final</span> <span class="token class-name">String</span> s1 <span class="token operator">=</span> <span class="token string">"hello"</span><span class="token punctuation">;</span><span class="token comment">//现在他是一个常量了</span>
<span class="token class-name">String</span> s2 <span class="token operator">=</span> <span class="token string">"hello"</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s1 <span class="token operator">+</span> <span class="token string">"java"</span> <span class="token operator">==</span> s<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s2 <span class="token operator">+</span> <span class="token string">"java"</span> <span class="token operator">==</span> s<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//false</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>s存储在常量池中，s1、s2相同，正常情况下参与运算会被看作是变量，变量地址加常量地址，当然不等于常量的地址了。但现在我们把s1标为常量，再去计算，就是常量间的运算（先将字符串拼接，然后发现常量池中已经有<code>&quot;hellojava&quot;</code>了，就直接使用之前的地址。），所以结果是true。</p>
<h2 id="常用方法"><a href="#常用方法" class="headerlink" title="常用方法"></a>常用方法</h2><p>字符串处理：<br><code>int length()</code>：返回字符串的长度： return value.length<br><code>char charAt(int index)</code>： 返回某索引处的字符return value[index]<br><code>boolean isEmpty()</code>：判断是否是空字符串：return value.length &#x3D;&#x3D; 0<br><code>String toLowerCase()</code>：使用默认语言环境，将 String 中的所有字符转换为小写<br><code>String toUpperCase()</code>：使用默认语言环境，将 String 中的所有字符转换为大写<br><code>String trim()</code>：返回字符串的副本，忽略前导空白和尾部空白<br><code>boolean equals(Object obj)</code>：比较字符串的内容是否相同<br><code>boolean equalsIgnoreCase(String anotherString)</code>：与equals方法类似，忽略大小写<br><code>String concat(String str)</code>：将指定字符串连接到此字符串的结尾。 等价于用“+”<br><code>int compareTo(String anotherString)</code>：比较两个字符串的大小<br><code>String substring(int beginIndex)</code>：返回一个新的字符串，它是此字符串的从beginIndex开始截取到最后的一个子字符串。<br><code>String substring(int beginIndex, int endIndex)</code> ：返回一个新字符串，它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。</p>
<blockquote>
<p>注意，只要涉及到开始索引和结束索引的方法，基本都是左闭右开。顾头不顾腚~</p>
</blockquote>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">" ab bc "</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//7</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//b</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//false</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// AB BC </span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">trim</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//ab bc</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"ac"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//false</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">equalsIgnoreCase</span><span class="token punctuation">(</span><span class="token string">" A Bc "</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//false</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token string">"def"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">// ab bc def</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span><span class="token string">"def"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//-68</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//ab bc</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<hr>
<p>前缀后缀：<br><code>boolean endsWith(String suffix)</code>：测试此字符串是否以指定的后缀结束<br><code>boolean startsWith(String prefix)</code>：测试此字符串是否以指定的前缀开始<br><code>boolean startsWith(String prefix, int toffset)</code>：测试此字符串从指定索引开始的子字符串是否以指定前缀开始</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"While the world sleep, you dream."</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">"Wh"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">"ile"</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">endsWith</span><span class="token punctuation">(</span><span class="token string">"eam."</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<p>查找字符：<br><code>boolean contains(CharSequence s)</code>：当且仅当此字符串包含指定的 char 值序列时，返回 true<br><code>int indexOf(String str)</code>：返回指定子字符串在此字符串中第一次出现处的索引<br><code>int indexOf(String str, int fromIndex)</code>：返回指定子字符串在此字符串中第一次出现处的索引，从指定的索引开始<br><code>int lastIndexOf(String str)</code>：返回指定子字符串在此字符串中最右边出现处的索引<br><code>int lastIndexOf(String str, int fromIndex)</code>：返回指定子字符串在此字符串中最后一次出现处的索引，从指定的索引开始反向搜索</p>
<p>注：<code>indexOf</code>和<code>lastIndexOf</code>方法如果未找到都是返回<code>-1</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"While the world sleep, you dream."</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span><span class="token string">"sleep"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span><span class="token string">"the"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//6</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span><span class="token string">"l"</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//13</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">lastIndexOf</span><span class="token punctuation">(</span><span class="token string">"l"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//17</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span><span class="token function">lastIndexOf</span><span class="token punctuation">(</span><span class="token string">"h"</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//1</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<p>替换<br><code>String replace(char oldChar, char newChar)</code>：返回一个新的字符串，它是通过用<code>newChar</code>替换此字符串中出现的所有<code>oldChar</code>得到的。<br><code>String replace(CharSequence target, CharSequence replacement)</code>：使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。<br><code>String replaceAll(String regex, String replacement)</code>：使用给定的<code>replacement</code>替换此字符串所有匹配给定的正则表达式的子字符串。<br><code>String replaceFirst(String regex, String replacement)</code>：使用给定的<code>replacement</code>替换此字符串匹配给定的正则表达式的第一个子字符串。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token string">"Tom is Tommy."</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token char">'T'</span><span class="token punctuation">,</span> <span class="token char">'J'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Jom is Jommy.</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token string">"Tom"</span><span class="token punctuation">,</span> <span class="token string">"Jim"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Jim is Jimmy.</span>
str <span class="token operator">=</span> <span class="token string">"12Tom34Tommy5"</span><span class="token punctuation">;</span>
<span class="token comment">//把字符串中的数字替换成,，如果结果中开头和结尾有，的话去掉</span>
<span class="token class-name">String</span> string <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">replaceAll</span><span class="token punctuation">(</span><span class="token string">"\\d+"</span><span class="token punctuation">,</span> <span class="token string">","</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">replaceAll</span><span class="token punctuation">(</span><span class="token string">"^,|,$"</span><span class="token punctuation">,</span> <span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>string<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Tom,Tommy</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<hr>
<p>匹配<br><code>boolean matches(String regex)</code>：告知此字符串是否匹配给定的正则表达式。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token string">"12345"</span><span class="token punctuation">;</span>
<span class="token comment">//判断str字符串中是否全部有数字组成，即有1-n个数字组成</span>
<span class="token keyword">boolean</span> matches <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">matches</span><span class="token punctuation">(</span><span class="token string">"\\d+"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>matches<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span>
<span class="token class-name">String</span> tel <span class="token operator">=</span> <span class="token string">"0571-4534289"</span><span class="token punctuation">;</span>
<span class="token comment">//判断这是否是一个杭州的固定电话</span>
<span class="token keyword">boolean</span> result <span class="token operator">=</span> tel<span class="token punctuation">.</span><span class="token function">matches</span><span class="token punctuation">(</span><span class="token string">"0571-\\d&#123;7,8&#125;"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//true</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<p>切片<br><code>String[] split(String regex)</code>：根据给定正则表达式的匹配拆分此字符串。<br><code>String[] split(String regex, int limit)</code>：根据匹配给定的正则表达式来拆分此字符串，最多不超过limit个，如果超过了，剩下的全部都放到最后一个元素中。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">str <span class="token operator">=</span> <span class="token string">"Tom|Tommy|Jimmy"</span><span class="token punctuation">;</span>
<span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> strs <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">"\\|"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> strs<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>strs<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
str <span class="token operator">=</span> <span class="token string">"Tom.Tommy.Jimmy"</span><span class="token punctuation">;</span>
<span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> strs2 <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">"\\."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> strs2<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>strs2<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">/*
Tom
Tommy
Jimmy

Tom
Tommy
Jimmy
*/</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="String-与基本数据类型、包装类之间的转换"><a href="#String-与基本数据类型、包装类之间的转换" class="headerlink" title="String 与基本数据类型、包装类之间的转换"></a>String 与基本数据类型、包装类之间的转换</h2><p>String –&gt; 基本数据类型、包装类：调用包装类的静态方法：<code>parseXxx(str)</code></p>
<p>基本数据类型、包装类 –&gt; String：调用String重载的<code>valueOf(xxx)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"123"</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token class-name">Integer</span><span class="token punctuation">.</span><span class="token function">parseInt</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//123</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//123</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="String-与-char-之间的转换"><a href="#String-与-char-之间的转换" class="headerlink" title="String 与 char[]之间的转换"></a>String 与 char[]之间的转换</h2><p>String –&gt; <code>char[]</code>：调用String的<code>toCharArray()</code></p>
<p><code>char[]</code>–&gt; String：调用String的构造器</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"hello"</span><span class="token punctuation">;</span>
<span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> chars <span class="token operator">=</span> s<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> chars<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>chars<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token class-name">String</span> s1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>chars<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="String-与-byte-之间的转换"><a href="#String-与-byte-之间的转换" class="headerlink" title="String 与 byte[]之间的转换"></a>String 与 byte[]之间的转换</h2><p>编码：String –&gt; <code>byte[]</code>:调用String的<code>getBytes()</code></p>
<p>​            字符串 –&gt;字节  (看得懂 —&gt;看不懂的二进制数据)</p>
<p>解码：<code>byte[]</code> –&gt; String:调用String的构造器</p>
<p>​            编码的逆过程，字节 –&gt; 字符串 （看不懂的二进制数据 —&gt; 看得懂）</p>
<p>说明：解码时，要求解码使用的字符集必须与编码时使用的字符集一致，否则会出现乱码。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"abc123爱你"</span><span class="token punctuation">;</span>
<span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> bytes <span class="token operator">=</span> s<span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>bytes<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//默认使用UTF-8编码</span>
<span class="token comment">//[97, 98, 99, 49, 50, 51, -25, -120, -79, -28, -67, -96]</span>
<span class="token class-name">String</span> s1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>bytes<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//解码，默认使用UTF-8</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//abc123爱你</span>

<span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> gbks <span class="token operator">=</span> s<span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token string">"gbk"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//使用gbk字符编码</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>gbks<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//[97, 98, 99, 49, 50, 51, -80, -82, -60, -29]</span>
<span class="token class-name">String</span> s2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>gbks<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//解码，默认使用UTF-8</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//abc123����</span>
<span class="token class-name">String</span> gbk <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>gbks<span class="token punctuation">,</span> <span class="token string">"gbk"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//解码，使用GBK</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>gbk<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//abc123爱你</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="练习题"><a href="#练习题" class="headerlink" title="练习题"></a>练习题</h2><h3 id="模拟一个trim方法，去除字符串两端的空格。"><a href="#模拟一个trim方法，去除字符串两端的空格。" class="headerlink" title="模拟一个trim方法，去除字符串两端的空格。"></a>模拟一个trim方法，去除字符串两端的空格。</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">trim</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//先把String转为Char数组</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> chars <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">//遍历数组，返回开头和末尾字符的索引</span>
    <span class="token keyword">int</span> foreIndex <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span> rearIndex <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">boolean</span> flag <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

    <span class="token comment">//查找首位字符索引</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> chars<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token char">' '</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"出现空格！现在记录空格索引："</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
            flag <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span><span class="token comment">//出现过空格了</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"出现了非空格内容。"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>flag <span class="token operator">==</span> <span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                foreIndex <span class="token operator">=</span> i<span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span><span class="token comment">//检测到出现非空格内容前有空格，记录该位置，并退出遍历</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"--------------"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//查找末位字符索引</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> chars<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>i <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token char">' '</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"出现空格！现在记录空格索引："</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
            flag <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span><span class="token comment">//出现过空格了</span>
        <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"出现了非空格内容。"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>flag <span class="token operator">==</span> <span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                rearIndex <span class="token operator">=</span> i<span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//如果首末位本身就有字符，直接返回</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">!=</span> <span class="token char">' '</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        foreIndex <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span>chars<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token char">' '</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        rearIndex <span class="token operator">=</span> chars<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">2</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"字符首位索引是："</span> <span class="token operator">+</span> foreIndex<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"字符末位索引是："</span> <span class="token operator">+</span> rearIndex<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//取出新的字符串        </span>
    <span class="token keyword">return</span> str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>foreIndex<span class="token punctuation">,</span> <span class="token operator">++</span>rearIndex<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>源码对比分析：</p>
<blockquote>
<p>Returns a string whose value is this string, with any leading and trailing whitespace removed.</p>
<p>If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than ‘\u0020’ (the space character), then a reference to this String object is returned.</p>
<p>Otherwise, if there is no character with a code greater than ‘\u0020’ in the string, then a String object representing an empty string is returned.</p>
<p>Otherwise, let k be the index of the first character in the string whose code is greater than ‘\u0020’, and let m be the index of the last character in the string whose code is greater than ‘\u0020’. A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m + 1).</p>
<p>This method may be used to trim whitespace (as defined above) from the beginning and end of a string.</p>
<p>Returns:</p>
<p>A string whose value is this string, with any leading and trailing white space removed, or this string if it has no leading or trailing white space.</p>
<p>External and inferred annotations:</p>
<p>@org.jetbrains.annotations.NotNull @org.jetbrains.annotations.Contract(pure &#x3D; true)</p>
</blockquote>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">trim</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> len <span class="token operator">=</span> value<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
    <span class="token keyword">int</span> st <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span><span class="token comment">//记录字串首位索引</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> val <span class="token operator">=</span> value<span class="token punctuation">;</span>    <span class="token comment">/* avoid getfield opcode 避免获取字段操作码 */</span>

    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>st <span class="token operator">&lt;</span> len<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token punctuation">(</span>val<span class="token punctuation">[</span>st<span class="token punctuation">]</span> <span class="token operator">&lt;=</span> <span class="token char">' '</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        st<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>st <span class="token operator">&lt;</span> len<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token punctuation">(</span>val<span class="token punctuation">[</span>len <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">&lt;=</span> <span class="token char">' '</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token comment">//此时st &lt; len表示判断到子串开头即可</span>
        len<span class="token operator">--</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>st <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token punctuation">(</span>len <span class="token operator">&lt;</span> value<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token function">substring</span><span class="token punctuation">(</span>st<span class="token punctuation">,</span> len<span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>来看第一个循环，<code>st &lt; len</code>的条件表示首位索引小于字符串长度，保证循环整个字符串。<code>val[st] &lt;= &#39; &#39;</code>的条件表示字符的编码小于空格（空格编码为32），如果两个条件都满足说明出现空格等字符，不满足则要么是开头没有出现空格，要么是整个字符串都是空格。</p>
<p>第二个循环是从后向前遍历，同时查看是否为空格等字符，两个条件都满足，说明出现空格，不满足要么末尾没有出现空格，要么是整个字符串都是空格。</p>
<p>最后<code>(st &gt; 0) || (len &lt; value.length)</code>条件通过（st和len发生了改变）表示：</p>
<ul>
<li>前后任意位置发现了空格 –&gt; <code>substring(st, len)</code>取子串</li>
<li>字符串全为空格 –&gt;  <code>substring(st, len)</code>取子串，会返回空的字符串</li>
</ul>
<h3 id="将一个字符串进行反转。将字符串中指定部分进行反转。"><a href="#将一个字符串进行反转。将字符串中指定部分进行反转。" class="headerlink" title="将一个字符串进行反转。将字符串中指定部分进行反转。"></a>将一个字符串进行反转。将字符串中指定部分进行反转。</h3><p>比如“abcdefg”反转为”abfedcg”</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
* 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
* @param startIndex 反转字符串开头索引
* @param endIndex  反转字符串末尾索引
* @return 反转后的数组
*/</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">reverse</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token keyword">int</span> startIndex<span class="token punctuation">,</span><span class="token keyword">int</span> endIndex<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> chars <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//反转数组</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> reverse <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token keyword">char</span><span class="token punctuation">[</span>chars<span class="token punctuation">.</span>length<span class="token punctuation">]</span><span class="token punctuation">;</span>
    reverse <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">copyOf</span><span class="token punctuation">(</span>chars<span class="token punctuation">,</span> chars<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//先把之前的数组复制一份</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> startIndex<span class="token punctuation">,</span>j <span class="token operator">=</span> endIndex<span class="token punctuation">;</span> i <span class="token operator">&lt;</span> endIndex <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">,</span>j<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        reverse<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> chars<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>reverse<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//改进后</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">reverse</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token keyword">int</span> startIndex<span class="token punctuation">,</span><span class="token keyword">int</span> endIndex<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> chars <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//反转数组</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> startIndex<span class="token punctuation">,</span>j <span class="token operator">=</span> endIndex<span class="token punctuation">;</span> i <span class="token operator">&lt;</span> j<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">,</span>j<span class="token operator">--</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token comment">//i &lt; j是该算法的精髓</span>
        <span class="token keyword">char</span> temp <span class="token operator">=</span> chars<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
        chars<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> chars<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
        chars<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> temp<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>chars<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//方式三：使用String的拼接</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">reverse</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token keyword">int</span> startIndex<span class="token punctuation">,</span><span class="token keyword">int</span> endIndex<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>str <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//第一部分</span>
    <span class="token class-name">String</span> s <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> startIndex<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//第二部分</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> endIndex<span class="token punctuation">;</span>i <span class="token operator">>=</span> startIndex<span class="token punctuation">;</span>i<span class="token operator">--</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        s <span class="token operator">+=</span> str<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//第三部分</span>
    s <span class="token operator">+=</span> str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>endIndex<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> s<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//方式四：使用StringBuilder的拼接</span>
<span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">reverse</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span> <span class="token keyword">int</span> startIndex<span class="token punctuation">,</span><span class="token keyword">int</span> endIndex<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>str <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//第一部分</span>
    <span class="token class-name">StringBuilder</span> s <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> startIndex<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//第二部分</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> endIndex<span class="token punctuation">;</span>i <span class="token operator">>=</span> startIndex<span class="token punctuation">;</span>i<span class="token operator">--</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        s<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">charAt</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//第三部分</span>
    s<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>endIndex<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> s<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="获取一个字符串在另一个字符串中出现的次数。"><a href="#获取一个字符串在另一个字符串中出现的次数。" class="headerlink" title="获取一个字符串在另一个字符串中出现的次数。"></a>获取一个字符串在另一个字符串中出现的次数。</h3><p>比如：获取“ ab”在 “abkkcadkabkebfkabkskab” 中出现的次数</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/**
* 获取一个字符串在另一个字符串中出现的次数。
*       比如：获取“ ab”在 “abkkcadkabkebfkabkskab” 中出现的次数
* @param str 要受检测的字符串
* @param checkStr 要检测的子串
* @return 如果出现，返回次数，如果没出现返回0
*/</span>
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getCount</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span><span class="token class-name">String</span> checkStr<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> chars <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> checkChars <span class="token operator">=</span> checkStr<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    outter<span class="token operator">:</span><span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> chars<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">!=</span> checkChars<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">continue</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span>k <span class="token operator">=</span> i<span class="token punctuation">;</span> j <span class="token operator">&lt;</span> checkChars<span class="token punctuation">.</span>length<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">,</span>k<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">!=</span> checkChars<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                <span class="token keyword">continue</span> outter<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        count<span class="token operator">++</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> count<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//方式二：利用indexOf()检查字符串</span>
<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getCount</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">,</span><span class="token class-name">String</span> checkStr<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> checkStr<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">int</span> count <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span>index <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token comment">//循环字符串直到找不到为止</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>index <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span>checkStr<span class="token punctuation">,</span>index<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        count<span class="token operator">++</span><span class="token punctuation">;</span>
        index <span class="token operator">+=</span> checkStr<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//每次开始寻找的位置==上次找到的字符出现位置+字符长度</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> count<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="获取两个字符串中最大相同子串。"><a href="#获取两个字符串中最大相同子串。" class="headerlink" title="获取两个字符串中最大相同子串。"></a>获取两个字符串中最大相同子串。</h3><p>比如：<code>str1 = &quot;abcwerthelloyuiodef“;``str2 = &quot;cvhellobnm&quot;</code><br>提示：将短的那个串进行长度依次递减的子串与较长的串比较。<br>前提：两个字符串中只有一个最大相同字串。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getMaxSubString</span><span class="token punctuation">(</span><span class="token class-name">String</span> str1<span class="token punctuation">,</span><span class="token class-name">String</span> str2<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token class-name">String</span> longerStr <span class="token operator">=</span> <span class="token punctuation">(</span>str1<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">></span> str2<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token operator">?</span> str1<span class="token operator">:</span>str2<span class="token punctuation">;</span>
    <span class="token class-name">String</span> shortStr <span class="token operator">=</span> <span class="token punctuation">(</span>str1<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&lt;=</span> str2<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token operator">?</span> str1<span class="token operator">:</span>str2<span class="token punctuation">;</span>
    <span class="token keyword">int</span> length <span class="token operator">=</span> shortStr<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">,</span>k <span class="token operator">=</span> length <span class="token operator">-</span> i<span class="token punctuation">;</span> k <span class="token operator">&lt;=</span> length<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">,</span>k<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token comment">//k &lt;= length k现在是索引数，要能取到才行</span>
            <span class="token class-name">String</span> subString <span class="token operator">=</span> shortStr<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>j<span class="token punctuation">,</span>k<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>longerStr<span class="token punctuation">.</span><span class="token function">contains</span><span class="token punctuation">(</span>subString<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                <span class="token keyword">return</span> subString<span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="对字符串中字符进行自然顺序排序。"><a href="#对字符串中字符进行自然顺序排序。" class="headerlink" title="对字符串中字符进行自然顺序排序。"></a>对字符串中字符进行自然顺序排序。</h3><p>提示：</p>
<ol>
<li><p>字符串变成字符数组。</p>
</li>
<li><p>对数组排序，选择，冒泡，<code>Arrays.sort();</code></p>
</li>
<li><p>将排序后的数组变成字符串。</p>
</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">sort</span><span class="token punctuation">(</span><span class="token class-name">String</span> str<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">char</span><span class="token punctuation">[</span><span class="token punctuation">]</span> chars <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">toCharArray</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>chars<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//方式一：系统快排</span>
    <span class="token comment">//方式二：手写冒泡</span>
    <span class="token keyword">boolean</span> is_swap <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> chars<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> chars<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>chars<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">></span> chars<span class="token punctuation">[</span>j<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                <span class="token keyword">char</span> temp <span class="token operator">=</span> chars<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">;</span>
                chars<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> chars<span class="token punctuation">[</span>j<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
                chars<span class="token punctuation">[</span>j<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> temp<span class="token punctuation">;</span>
                is_swap <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>is_swap<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
                is_swap <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span>chars<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h1 id="StringBuffer、StringBuilder类"><a href="#StringBuffer、StringBuilder类" class="headerlink" title="StringBuffer、StringBuilder类"></a>StringBuffer、StringBuilder类</h1><h3 id="与String比较"><a href="#与String比较" class="headerlink" title="与String比较"></a>与String比较</h3><p>String、StringBuffer、StringBuilder三者的异同？</p>
<ul>
<li>String：不可变的字符序列；底层使用<code>char[]</code>存储</li>
<li>StringBuffer：可变的字符序列；线程安全的，效率低；底层使用<code>char[]</code>存储</li>
<li>StringBuilder：可变的字符序列；jdk5.0新增的，线程不安全的，效率高；底层使用<code>char[]</code>存储</li>
</ul>
<p>源码分析：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> str <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//char[] value = new char[0];</span>
<span class="token class-name">String</span> str1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token string">"abc"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//char[] value = new char[]&#123;'a','b','c'&#125;;</span>

<span class="token class-name">StringBuffer</span> sb1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuffer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//char[] value = new char[16];底层创建了一个长度是16的数组。</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>sb1<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//0，显示的是实际写入的字符长度。</span>
sb1<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token char">'a'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//value[0] = 'a';</span>
sb1<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token char">'b'</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//value[1] = 'b';</span>

<span class="token class-name">StringBuffer</span> sb2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuffer</span><span class="token punctuation">(</span><span class="token string">"abc"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//char[] value = new char["abc".length() + 16];</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>问题1. <code>System.out.println(sb2.length());</code>输出结果为？</p>
<p>答案：3。只写入了3个字符。而底层<code>char[]</code>数组的长度为19。</p>
<p>问题2. 扩容问题：如果要添加的数据底层数组盛不下了，那就需要扩容底层的数组。如何进行扩容</p>
<p>答案：默认情况下，扩容为原来容量的2倍 + 2，同时将原有数组中的元素复制到新的数组中。</p>
<p>指导意义：</p>
<p>​    开发中建议大家使用：<code>StringBuffer(int capacity)</code>或<code>StringBuilder(int capacity)</code>，因为它们可以改变长度随时修改数据，再根据是否需要解决线程安全，选其一（需要线程安全选<code>StringBuffer(int capacity)</code>）。</p>
<h3 id="其常用方法"><a href="#其常用方法" class="headerlink" title="其常用方法"></a>其常用方法</h3><p>有以下方法：<br><code>StringBuffer append(xxx)</code>：提供了很多的<code>append()</code>方法，用于进行字符串拼接<br><code>StringBuffer delete(int start,int end)</code>：删除指定位置的内容<br><code>StringBuffer replace(int start, int end, String str)</code>：把[start,end)位置替换为str<br><code>StringBuffer insert(int offset, xxx)</code>：在指定位置插入xxx<br><code>StringBuffer reverse()</code> ：把当前字符序列逆转<br><code>public int indexOf(String str)</code><br><code>public String substring(int start,int end)</code>:返回一个从start开始到end索引结束的左闭右开区间的子字符串<br><code>public int length()</code><br><code>public char charAt(int n )</code><br><code>public void setCharAt(int n ,char ch)</code></p>
<p>总结：<br>        增：<code>append(xxx)</code><br>        删：<code>delete(int start,int end)</code><br>        改：<code>setCharAt(int n ,char ch)</code> &#x2F; <code>replace(int start, int end, String str)</code><br>        查：<code>charAt(int n)</code><br>        插：<code>insert(int offset, xxx)</code><br>        长度：<code>length();</code><br>        ⭐遍历：<code>for()</code> + <code>charAt()</code> &#x2F; <code>toString()</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">StringBuilder</span> str <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">StringBuilder</span><span class="token punctuation">(</span><span class="token string">"0123456"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
str<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token number">7</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//01234567</span>
str<span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//012345</span>
str<span class="token punctuation">.</span><span class="token function">setCharAt</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token char">'a'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//01234a</span>
str<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">6</span><span class="token punctuation">,</span><span class="token string">"45"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//012345</span>
str<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token string">"hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//012hello345</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//11</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>str<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//012hello345</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h1 id="Date类"><a href="#Date类" class="headerlink" title="Date类"></a>Date类</h1><h2 id="System类时间"><a href="#System类时间" class="headerlink" title="System类时间"></a>System类时间</h2><p>使用<code>System</code>类的<code>currentTimeMillis()</code>方法获取当前时间</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">long</span> time <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>time<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//1675588908461</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h2 id="JDK-8之前日期和时间的API"><a href="#JDK-8之前日期和时间的API" class="headerlink" title="JDK 8之前日期和时间的API"></a>JDK 8之前日期和时间的API</h2><h3 id="java-util-Date类及其子类"><a href="#java-util-Date类及其子类" class="headerlink" title="java.util.Date类及其子类"></a><code>java.util.Date</code>类及其子类</h3><p><code>java.util.Date</code>类<br>           |—<code>java.sql.Date</code>类</p>
<ol>
<li>两个构造器的使用<ul>
<li>构造器一：<code>Date()</code>：创建一个对应当前时间的Date对象</li>
<li>构造器二：创建指定毫秒数的Date对象</li>
</ul>
</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Date</span> date <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Date</span> date1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token number">1675563865916L</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//java.util.Date有两个</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ol start="2">
<li>两个方法的使用<ul>
<li><code>toString()</code>:显示当前的年、月、日、时、分、秒</li>
<li><code>getTime()</code>:获取当前Date对象对应的毫秒数。（时间戳）</li>
</ul>
</li>
</ol>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date<span class="token punctuation">.</span><span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//1675564133278</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Sun Feb 05 10:28:53 CST 2023</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ol start="3">
<li><p><code>java.sql.Date</code>对应着数据库中的日期类型的变量</p>
<ul>
<li><p>如何实例化</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span>Date</span> date2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span>Date</span><span class="token punctuation">(</span><span class="token number">1675563865916L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//java.sql.Date只有这一个构造器可用，必须填上时间戳</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date2<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-05	java.sql.Date只会输出年月日</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date2<span class="token punctuation">.</span><span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//1675563865916</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>如何将<code>java.util.Date</code>对象转换为<code>java.sql.Date</code>对象</p>
<p>通过时间戳</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Date</span> date1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token number">1675563865916L</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span>Date</span> date3 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span>Date</span><span class="token punctuation">(</span>date1<span class="token punctuation">.</span><span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date3<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></li>
</ul>
</li>
</ol>
<h3 id="SimpleDateFormat类"><a href="#SimpleDateFormat类" class="headerlink" title="SimpleDateFormat类"></a><code>SimpleDateFormat</code>类</h3><p>Date类的API不易于国际化，大部分被废弃了，<code>java.text.SimpleDateFormat</code>类是一个不与语言环境有关的方式来格式化和解析日期的具体类。</p>
<p>它允许进行</p>
<ul>
<li><p>格式化：日期–&gt;文本</p>
<p><code>SimpleDateFormat()</code>：默认的模式和语言环境创建对象</p>
<p><code>public SimpleDateFormat(String pattern)</code>：该构造方法可以用参数pattern指定的格式创建一个对象，该对象调用–&gt;<code>public String format(Date date)</code>方法格式化时间对象date</p>
</li>
<li><p>解析：文本–&gt;日期</p>
<p><code>public Date parse(String source)</code>：从给定字符串的开始解析文本，以生成一个日期。</p>
</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//使用默认构造器</span>
<span class="token class-name">SimpleDateFormat</span> sdf <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SimpleDateFormat</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> format <span class="token operator">=</span> sdf<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>format<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2/6/23 12:11 PM</span>

<span class="token comment">//解析</span>
<span class="token class-name">String</span> s <span class="token operator">=</span> <span class="token string">"2/6/23 11:25 AM"</span><span class="token punctuation">;</span>
<span class="token class-name">Date</span> date <span class="token operator">=</span> sdf<span class="token punctuation">.</span><span class="token function">parse</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Mon Feb 06 11:25:00 CST 2023</span>

<span class="token comment">//按照指定的方法格式化和解析，调用带参的构造器</span>
<span class="token class-name">SimpleDateFormat</span> dateFormat <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SimpleDateFormat</span><span class="token punctuation">(</span><span class="token string">"yyyy年MM月dd日 HH时mm分ss秒"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//格式化</span>
<span class="token class-name">String</span> format1 <span class="token operator">=</span> dateFormat<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>format1<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023年02月06日 12时19分47秒</span>
<span class="token comment">//解析,解析时必须使用与SimpleDateFormat相同的日期格式</span>
<span class="token class-name">Date</span> parse1 <span class="token operator">=</span> dateFormat<span class="token punctuation">.</span><span class="token function">parse</span><span class="token punctuation">(</span><span class="token string">"2023年02月06日 12时18分56秒"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>parse1<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Mon Feb 06 12:18:56 CST 2023</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>日期格式的字母含义：</p>
<img src="https://s2.loli.net/2023/02/06/45MAlR8uheUOcqK.png" alt="image-20230206150552876" style="zoom:50%;" />

<h3 id="Calendar类"><a href="#Calendar类" class="headerlink" title="Calendar类"></a><code>Calendar</code>类</h3><p><code>Calendar</code>是一个抽象基类，主用用于完成日期字段之间相互操作的功能。</p>
<p>获取Calendar实例的方法</p>
<ul>
<li><p>使用<code>Calendar.getInstance()</code>方法</p>
<p><code>Calendar calendar = Calendar.getInstance();</code>即可实例化</p>
</li>
<li><p>调用它的子类<code>GregorianCalendar</code>的构造器。（不常用）</p>
</li>
</ul>
<p> 一个Calendar的实例是系统时间的抽象表示，通过<code>get(int field)</code>方法来取得想要的时间信息。比如<code>YEAR</code>、<code>MONTH</code>、<code>DAY_OF_WEEK</code>、<code>HOUR_OF_DAY</code> 、<code>MINUTE</code>、<code>SECOND</code></p>
<ul>
<li><p><code>public void get(int field,int value)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">int</span> days <span class="token operator">=</span> calendar<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token class-name">Calendar</span><span class="token punctuation">.</span>DAY_OF_MONTH<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>days<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//6</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
</li>
<li><p><code>public void set(int field,int value)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">calendar<span class="token punctuation">.</span><span class="token function">set</span><span class="token punctuation">(</span><span class="token class-name">Calendar</span><span class="token punctuation">.</span>DAY_OF_MONTH<span class="token punctuation">,</span><span class="token number">22</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">int</span> day <span class="token operator">=</span> calendar<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token class-name">Calendar</span><span class="token punctuation">.</span>DAY_OF_MONTH<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>day<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//22</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
<li><p><code>public void add(int field,int amount)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">calendar<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token class-name">Calendar</span><span class="token punctuation">.</span>DAY_OF_MONTH<span class="token punctuation">,</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>calendar<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token class-name">Calendar</span><span class="token punctuation">.</span>DAY_OF_MONTH<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//21</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>


</li>
<li><p>与Date转换</p>
<ul>
<li><p><code>public final Date getTime()</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Date</span> time <span class="token operator">=</span> calendar<span class="token punctuation">.</span><span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>time<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//21</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
</li>
<li><p><code>public final void setTime(Date date)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">calendar<span class="token punctuation">.</span><span class="token function">setTime</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>calendar<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token class-name">Calendar</span><span class="token punctuation">.</span>DAY_OF_MONTH<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//6</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre></li>
</ul>
</li>
</ul>
<p> 注意：</p>
<ul>
<li>获取月份时：一月是0，二月是1，以此类推，12月是11</li>
<li>获取星期时：周日是1，周二是2  。。。。。周六是7</li>
</ul>
<h2 id="JDK-8中新的日期和时间API"><a href="#JDK-8中新的日期和时间API" class="headerlink" title="JDK 8中新的日期和时间API"></a>JDK 8中新的日期和时间API</h2><p>为啥要引入新的时间api？来看看旧版api有多变态</p>
<p>用我们之前的Date类生成2023年2月6日的日期</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Date</span> date <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token number">2023</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//你以为是这样？</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Tue Mar 06 00:00:00 CST 3923</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>错了，这样给出的是3923年3月6日，只有日是对的。这是因为Date中的年份是从1900开始的，而月份都从0开始。所以要想得到正确的日期，必须要使用偏移量。像这样：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Date</span> date <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token number">2023</span> <span class="token operator">-</span> <span class="token number">1900</span><span class="token punctuation">,</span> <span class="token number">2</span> <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>date<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//Mon Feb 06 00:00:00 CST 2023</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>太变态了，不过幸好有外部的包可以使用，它叫做：<code>Joda-Time</code>，java8之前我们通过maven引入即可，java8之后官方引入了这个包，我们可以直接使用。</p>
<h3 id="java-time"><a href="#java-time" class="headerlink" title="java.time"></a>java.time</h3><p>java新的日期包有：</p>
<blockquote>
<p><code>java.time</code> – 包含值对象的基础包<br>       <code>java.time.chrono</code> – 提供对不同的日历系统的访问<br>       <code>java.time.format</code> – 格式化和解析时间和日期<br>       <code>java.time.temporal</code> – 包括底层框架和扩展特性<br>       <code>java.time.zone</code> – 包含时区支持的类</p>
</blockquote>
<p> <code>LocalDate、LocalTime、LocalDateTime</code> 类是其中较重要的几个类，它们的实例是不可变的对象，分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间，并不包含当前的时间信息，也不包含与时区相关的信息。</p>
<ul>
<li>LocalDate代表IOS格式（yyyy-MM-dd）的日期,可以存储 生日、纪念日等日期。</li>
<li>LocalTime表示一个时间，而不是日期。</li>
<li>LocalDateTime是用来表示日期和时间的，这是一个最常用的类之一。</li>
</ul>
<p>这三个类拥有相同的方法，不同的是只包含日期或时间而已。<code>LocalDateTime</code>最常用。</p>
<p>方法列举：</p>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>now() / now(ZoneId zone)</code></td>
<td align="center">静态方法，根据当前时间创建对象&#x2F;指定时区的对象</td>
</tr>
<tr>
<td align="center"><code>of()</code></td>
<td align="center">静态方法，根据指定日期&#x2F;时间创建对象</td>
</tr>
<tr>
<td align="center"><code>getDayOfMonth()/getDayOfYear()</code></td>
<td align="center">获得月份天数(1-31) &#x2F;获得年份天数(1-366)</td>
</tr>
<tr>
<td align="center"><code>getDayOfWeek()</code></td>
<td align="center">获得星期几(返回一个 DayOfWeek 枚举值)</td>
</tr>
<tr>
<td align="center"><code>getMonth()</code></td>
<td align="center">获得月份, 返回一个 Month 枚举值</td>
</tr>
<tr>
<td align="center"><code>getMonthValue() / getYear()</code></td>
<td align="center">获得月份(1-12) &#x2F;获得年份</td>
</tr>
<tr>
<td align="center"><code>getHour()/getMinute()/getSecond()</code></td>
<td align="center">获得当前对象对应的小时、分钟、秒</td>
</tr>
<tr>
<td align="center"><code>withDayOfMonth()/withDayOfYear()/</code><br/><code>withMonth()/withYear()</code></td>
<td align="center">将月份天数、年份天数、月份、年份<br/>修改为指定的值并返回新的对象</td>
</tr>
<tr>
<td align="center"><code>plusDays()/plusWeeks()</code><br/><code>plusMonths()/plusYears()/plusHours()</code></td>
<td align="center">向当前对象添加几天、几周、<br>几个月、几年、几小时</td>
</tr>
<tr>
<td align="center"><code>minusMonths() / minusWeeks()/</code><br/><code>minusDays()/minusYears()/minusHours()</code></td>
<td align="center">从当前对象减去几月、几周、几天、<br/>几年、几小时</td>
</tr>
</tbody></table>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//now()方法获取当前时间</span>
<span class="token class-name">LocalDate</span> localDate <span class="token operator">=</span> <span class="token class-name">LocalDate</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDate<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-06</span>
<span class="token class-name">LocalTime</span> localTime <span class="token operator">=</span> <span class="token class-name">LocalTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localTime<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//22:35:26.178</span>
<span class="token class-name">LocalDateTime</span> localDateTime <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>localDateTime<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-06T22:35:26.178</span>

<span class="token comment">//of()</span>
<span class="token class-name">LocalDateTime</span> dateTime <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token number">2023</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">53</span><span class="token punctuation">,</span> <span class="token number">23</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>dateTime<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-06T22:53:23</span>

<span class="token comment">//getXxx()</span>
<span class="token class-name">LocalDateTime</span> now <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">getDayOfMonth</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//6</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">getDayOfWeek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//MONDAY</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">getMonth</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//FEBRUARY</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">getMinute</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">getHour</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//23</span>

<span class="token comment">//withXxx(),修改时间。由于不可变性，所以返回一个日期对象。</span>
<span class="token class-name">LocalDateTime</span> now <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">withHour</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//修改时间为3点：2023-02-06T03:13:50.929</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">withDayOfMonth</span><span class="token punctuation">(</span><span class="token number">22</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//修改日期为22号：2023-02-22T23:13:50.929</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">withDayOfYear</span><span class="token punctuation">(</span><span class="token number">234</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//修改日期为一年中的第234天：2023-08-22T23:13:50.929</span>

<span class="token comment">//plusXxx()，加上一段时间。由于不可变性，所以返回一个日期对象。</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">plusMonths</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-04-06T23:33:21.147</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">plusDays</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-09T23:33:21.147</span>

<span class="token comment">//minusXxx()，减去一段时间。由于不可变性，所以返回一个日期对象。</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">minusDays</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-04T23:34:58.746</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">minusHours</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-06T20:34:58.746</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="瞬时：Instant"><a href="#瞬时：Instant" class="headerlink" title="瞬时：Instant"></a>瞬时：Instant</h3><p>Instant：时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳。</p>
<p><code>java.time</code>包通过值类型<code>Instant</code>提供机器视图，不提供处理人类意义上的时间单位。<code>Instant</code>表示时间线上的一点，而不需要任何上下文信息，例如，时区。概念上讲，它只是简单的表示自1970年1月1日0时0分0秒（UTC）开始的秒数。因为<code>java.time</code>包是基于纳秒计算的，所以Instant的精度可以达到纳秒级。</p>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>now()</code></td>
<td align="center"><strong>静态方法</strong>，返回默认UTC时区的Instant类的对象</td>
</tr>
<tr>
<td align="center"><code>ofEpochMilli(long epochMilli)</code></td>
<td align="center"><strong>静态方法</strong>，返回在1970-01-01 00:00:00基础上<br/>加上指定毫秒数之后的Instant类的对象</td>
</tr>
<tr>
<td align="center"><code>atOffset(ZoneOffset offset)</code></td>
<td align="center">结合即时的偏移来创建一个 OffsetDateTime</td>
</tr>
<tr>
<td align="center"><code>toEpochMilli()</code></td>
<td align="center">返回1970-01-01 00:00:00到当前时间的毫秒数，即为时间戳</td>
</tr>
</tbody></table>
<p>使用示例：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Instant</span> instant <span class="token operator">=</span> <span class="token class-name">Instant</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instant<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-06T15:58:40.700Z</span>
<span class="token comment">//默认提供的是本初子午线时间，北京时间加上8小时即可</span>
<span class="token class-name">OffsetDateTime</span> beijingTime <span class="token operator">=</span> instant<span class="token punctuation">.</span><span class="token function">atOffset</span><span class="token punctuation">(</span><span class="token class-name">ZoneOffset</span><span class="token punctuation">.</span><span class="token function">ofHours</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//atOffset()方法调整时差</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>beijingTime<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-06T23:58:40.700+08:00</span>

<span class="token keyword">long</span> milli <span class="token operator">=</span> instant<span class="token punctuation">.</span><span class="token function">toEpochMilli</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//获取时间戳（自1970年1月1日0时0分0秒（UTC）开始的秒数）</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>milli<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//1675699348497</span>

<span class="token class-name">Instant</span> instant <span class="token operator">=</span> <span class="token class-name">Instant</span><span class="token punctuation">.</span><span class="token function">ofEpochMilli</span><span class="token punctuation">(</span><span class="token number">1675700191827L</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//以某一时刻shi'li</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>instant<span class="token punctuation">.</span><span class="token function">atOffset</span><span class="token punctuation">(</span><span class="token class-name">ZoneOffset</span><span class="token punctuation">.</span><span class="token function">ofHours</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//2023-02-07T00:16:31.827+08:00	为了更好展示添加了时区</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="DateTimeFormatter类"><a href="#DateTimeFormatter类" class="headerlink" title="DateTimeFormatter类"></a><code>DateTimeFormatter</code>类</h3><p><code>java.time.format.DateTimeFormatter</code>类：该类提供了三种格式化方法：</p>
<ul>
<li><p>预定义的标准格式。（不常用）</p>
<p>如：<code>ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">DateTimeFormatter</span> formatter <span class="token operator">=</span> <span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span>ISO_LOCAL_DATE_TIME<span class="token punctuation">;</span>

<span class="token comment">//为了显示出来，我们进行格式化</span>
<span class="token class-name">LocalDateTime</span> now <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> format <span class="token operator">=</span> formatter<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span>now<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>format<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-07T10:36:22.118</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>此时生成的是一个格式，将实现<code>java.time.temporal.TemporalAccessor</code>接口的时间对象放进它的<code>format()</code>方法就可以实例化一个标准格式的时间。</p>
</li>
<li><p>本地化相关的格式。如：<code>ofLocalizedDateTime(FormatStyle.LONG)</code></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">DateTimeFormatter</span> formatter <span class="token operator">=</span> <span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span><span class="token function">ofLocalizedDateTime</span><span class="token punctuation">(</span><span class="token class-name">FormatStyle</span><span class="token punctuation">.</span>LONG<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">withZone</span><span class="token punctuation">(</span><span class="token class-name">ZoneId</span><span class="token punctuation">.</span><span class="token function">systemDefault</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">LocalDateTime</span> now <span class="token operator">=</span> <span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> formated_time <span class="token operator">=</span> formatter<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span>now<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>formated_time<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//February 7, 2023 11:01:28 AM CT</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>注意：使用<code>FormatStyle.LONG</code>格式时可能会碰到unchecked异常，加上时区即可。</p>
<p>根据<a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/48731863/datetimeexception-while-using-datetimeformatter-oflocalizedtimeformatstyle-full">社区中的回答</a>，这大概率是LONG格式在输出时需要时区信息，而formatter中默认没有这个信息，导致了错误。</p>
</li>
<li><p>自定义的格式。如：<code>ofPattern(“yyyy-MM-dd hh:mm:ss”)</code>（最常用）</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">DateTimeFormatter</span> formatter <span class="token operator">=</span> <span class="token class-name">DateTimeFormatter</span><span class="token punctuation">.</span><span class="token function">ofPattern</span><span class="token punctuation">(</span><span class="token string">"yyyy-MM-dd hh:mm:ss"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">String</span> formated_time <span class="token operator">=</span> formatter<span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span><span class="token class-name">LocalDateTime</span><span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>formated_time<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//2023-02-07 11:10:24</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre></li>
</ul>
<p>方法列表：</p>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>ofPattern(String pattern)</code></td>
<td align="center">静 态 方 法 ， 返 回 一 个 指 定 <br/>字 符 串 格 式 的<code>DateTimeFormatter</code></td>
</tr>
<tr>
<td align="center"><code>format(TemporalAccessor t)</code></td>
<td align="center">格式化一个日期、时间，返回字符串</td>
</tr>
<tr>
<td align="center"><code>parse(CharSequence text)</code></td>
<td align="center">将指定格式的字符序列解析为一个日期、时间</td>
</tr>
</tbody></table>
<h3 id="其它API"><a href="#其它API" class="headerlink" title="其它API"></a>其它API</h3><ul>
<li><code>ZoneId</code>：该类中包含了所有的时区信息，一个时区的ID，如 <code>Europe/Paris</code></li>
<li><code>ZonedDateTime</code>：一个在ISO-8601日历系统时区的日期时间，如 2007-12-03T10:15:30+01:00 Europe&#x2F;Paris。</li>
<li>其中每个时区都对应着ID，地区ID都为“{区域}&#x2F;{城市}”的格式，例如：Asia&#x2F;Shanghai等</li>
<li>Clock：使用时区提供对当前即时、日期和时间的访问的时钟。</li>
<li>持续时间：Duration，用于计算两个“时间”间隔</li>
<li>日期间隔：Period，用于计算两个“日期”间隔</li>
<li><code>TemporalAdjuster</code> : 时间校正器。有时我们可能需要获取例如：将日期调整到“下一个工作日”等操作。</li>
<li><code>TemporalAdjusters</code> : 该类通过静态方法<code>firstDayOfXxx()/lastDayOfXxx()/nextXxx()</code>提供了大量的常用<code>TemporalAdjuster</code>的实现。</li>
</ul>
<h4 id="参考：与传统日期处理的转换"><a href="#参考：与传统日期处理的转换" class="headerlink" title="参考：与传统日期处理的转换"></a>参考：与传统日期处理的转换</h4><table>
<thead>
<tr>
<th align="center">类</th>
<th align="right">To 遗留类</th>
<th align="left">From 遗留类</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>java.time.Instant</code>与<code>java.util.Date</code></td>
<td align="right"><code>Date.from(instant)</code></td>
<td align="left"><code>Date.from(instant)</code></td>
</tr>
<tr>
<td align="center"><code>java.time.Instant</code>与<code> java.sql.Timestamp</code></td>
<td align="right"><code>Timestamp.from(instant)</code></td>
<td align="left"><code>timestamp.toInstant()</code></td>
</tr>
<tr>
<td align="center"><code>java.time.ZonedDateTime</code>与<code>java.util.GregorianCalendar</code></td>
<td align="right"><code>GregorianCalendar.from(zonedDateTime)</code></td>
<td align="left"><code>cal.toZonedDateTime()</code></td>
</tr>
<tr>
<td align="center"><code>java.time.LocalDate/LocalTime</code>与 <code>java.sql.Time</code></td>
<td align="right"><code>Date.valueOf(localDate)</code></td>
<td align="left"><code>date.toLocalDate()</code></td>
</tr>
<tr>
<td align="center"><code>java.time.LocalDateTime</code>与<code>java.sql.Timestamp</code></td>
<td align="right"><code>Timestamp.valueOf(localDateTime)</code></td>
<td align="left"><code>timestamp.toLocalDateTime()</code></td>
</tr>
<tr>
<td align="center"><code>java.time.ZoneId</code>与 <code>java.util.TimeZone</code></td>
<td align="right"><code>Timezone.getTimeZone(id)</code></td>
<td align="left"><code>timeZone.toZoneId()</code></td>
</tr>
<tr>
<td align="center"><code>java.time.format.DateTimeFormatter</code> 与<code>java.text.DateFormat</code></td>
<td align="right"><code>formatter.toFormat()</code></td>
<td align="left">无</td>
</tr>
</tbody></table>
<h1 id="比较类"><a href="#比较类" class="headerlink" title="比较类"></a>比较类</h1><p>在Java中经常会涉及到对象数组的排序问题，那么就涉及到对象之间的比较问题。</p>
<p>Java实现对象排序的方式有两种：</p>
<ul>
<li>自然排序：<code>java.lang.Comparable</code></li>
<li>定制排序：<code>java.util.Comparator</code></li>
</ul>
<h2 id="Comparable接口-自然排序"><a href="#Comparable接口-自然排序" class="headerlink" title="Comparable接口-自然排序"></a>Comparable接口-自然排序</h2><h3 id="对于String类、包装类"><a href="#对于String类、包装类" class="headerlink" title="对于String类、包装类"></a>对于String类、包装类</h3><p>像String、包装类等实现了<code>Comparable</code>接口，重写了<code>compareTo(obj)</code>方法，给出了比较两个对象大小的方式。重写<code>compareTo(obj)</code>方法以后，进行了从小到大的排列。我们直接使用即可</p>
<p>重写<code>compareTo(obj)</code>的规则：</p>
<blockquote>
<p>如果当前对象this大于形参对象obj，则返回正整数</p>
<p>如果当前对象this小于形参对象obj，则返回负整数</p>
<p>如果当前对象this等于形参对象obj，则返回零。</p>
</blockquote>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">&#123;</span><span class="token string">"AA"</span><span class="token punctuation">,</span><span class="token string">"CC"</span><span class="token punctuation">,</span><span class="token string">"KK"</span><span class="token punctuation">,</span><span class="token string">"MM"</span><span class="token punctuation">,</span><span class="token string">"GG"</span><span class="token punctuation">,</span><span class="token string">"JJ"</span><span class="token punctuation">,</span><span class="token string">"DD"</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//内部调用了重写的compareTo(obj)方法</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//[AA, CC, DD, GG, JJ, KK, MM]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="对于自定义类"><a href="#对于自定义类" class="headerlink" title="对于自定义类"></a>对于自定义类</h3><p>对于自定义类来说，如果需要排序，我们可以让自定义类实现<code>Comparable</code>接口，重写<code>compareTo(obj)</code>方法。在<code>compareTo(obj)</code>方法中指明如何排序。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Person</span> <span class="token keyword">implements</span> <span class="token class-name">Comparable</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> age<span class="token punctuation">;</span>

    <span class="token comment">/*
    省略构造器，String等方法
    */</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compareTo</span><span class="token punctuation">(</span><span class="token class-name">Object</span> o<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token punctuation">(</span>o <span class="token keyword">instanceof</span> <span class="token class-name">Person</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"传入的类型不是Person！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">Person</span> person <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Person</span><span class="token punctuation">)</span> o<span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">></span> person<span class="token punctuation">.</span>age<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">-</span> person<span class="token punctuation">.</span>age<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">&lt;</span> person<span class="token punctuation">.</span>age<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">-</span> person<span class="token punctuation">.</span>age<span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>person<span class="token punctuation">.</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//年龄相同比较姓名</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>接下来就可以进行比较</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Person</span><span class="token punctuation">[</span><span class="token punctuation">]</span> people <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">&#123;</span>
    people<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"恒星"</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"芽衣"</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"琪亚娜"</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"布洛尼亚"</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"无量塔 姬子"</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>people<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> people<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>people<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">/*
Person&#123;name='布洛尼亚', age=16&#125;
Person&#123;name='琪亚娜', age=18&#125;
Person&#123;name='芽衣', age=18&#125;
Person&#123;name='恒星', age=22&#125;
Person&#123;name='无量塔 姬子', age=22&#125;
*/</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Comparator接口-定制排序"><a href="#Comparator接口-定制排序" class="headerlink" title="Comparator接口-定制排序"></a>Comparator接口-定制排序</h2><p>当元素的类型没有实现<code>java.lang.Comparable</code>接口而又不方便修改代码，或者实现了<code>java.lang.Comparable</code>接口的排序规则不适合当前的操作，那么可以考虑使用<code>Comparator</code>的对象来排序。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">&#123;</span><span class="token string">"AA"</span><span class="token punctuation">,</span><span class="token string">"CC"</span><span class="token punctuation">,</span><span class="token string">"KK"</span><span class="token punctuation">,</span><span class="token string">"MM"</span><span class="token punctuation">,</span><span class="token string">"GG"</span><span class="token punctuation">,</span><span class="token string">"JJ"</span><span class="token punctuation">,</span><span class="token string">"DD"</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Comparator</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token comment">//自己定制一个排序方法，这个方法可能只是临时用一下</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">Object</span> o1<span class="token punctuation">,</span> <span class="token class-name">Object</span> o2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token punctuation">(</span>o1 <span class="token keyword">instanceof</span> <span class="token class-name">String</span> <span class="token operator">&amp;&amp;</span> o2 <span class="token keyword">instanceof</span> <span class="token class-name">String</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"传入的参数不是String类型。"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">String</span> s1 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span> o1<span class="token punctuation">;</span>
        <span class="token class-name">String</span> s2 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span> o2<span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token operator">-</span><span class="token punctuation">(</span>s1<span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//从高到低排列</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>对于自定义对象</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Person</span><span class="token punctuation">[</span><span class="token punctuation">]</span> people <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token punctuation">&#123;</span>
    people<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"恒星"</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"芽衣"</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"琪亚娜"</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"布洛尼亚"</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    people<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Person</span><span class="token punctuation">(</span><span class="token string">"无量塔 姬子"</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">//之前的排序不符合我们的要求，我们自己重新定制一个</span>
<span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>people<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Comparator</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Override</span><span class="token comment">//先按照姓名升序排列，再按照年龄升序排列</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span><span class="token class-name">Object</span> o1<span class="token punctuation">,</span> <span class="token class-name">Object</span> o2<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token punctuation">(</span>o1 <span class="token keyword">instanceof</span> <span class="token class-name">Person</span> <span class="token operator">&amp;&amp;</span> o2 <span class="token keyword">instanceof</span> <span class="token class-name">Person</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">RuntimeException</span><span class="token punctuation">(</span><span class="token string">"传入的类型不是Person！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token class-name">Person</span> person1 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Person</span><span class="token punctuation">)</span> o1<span class="token punctuation">;</span>
        <span class="token class-name">Person</span> person2 <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Person</span><span class="token punctuation">)</span> o2<span class="token punctuation">;</span>
        <span class="token comment">//方式一：</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>person1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>person2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">></span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token keyword">if</span><span class="token punctuation">(</span>person1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>person2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> person2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> person1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token comment">//方式二：这样似乎更好？</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>person1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>person2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> person2<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> person1<span class="token punctuation">.</span><span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span><span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">return</span> person1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span>person2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span>people<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">/*[Person&#123;name='布洛尼亚', age=16&#125;,
Person&#123;name='恒星', age=22&#125;,
Person&#123;name='无量塔 姬子', age=22&#125;,
Person&#123;name='琪亚娜', age=18&#125;,
Person&#123;name='芽衣', age=18&#125;]*/</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Comparable接口与Comparator的使用的对比"><a href="#Comparable接口与Comparator的使用的对比" class="headerlink" title="Comparable接口与Comparator的使用的对比"></a>Comparable接口与Comparator的使用的对比</h2><p>Comparable接口的方式一旦确定，保证Comparable接口实现类的对象在任何位置都可以比较大小。Comparator接口属于临时性的比较。</p>
<h1 id="其他类"><a href="#其他类" class="headerlink" title="其他类"></a>其他类</h1><h2 id="System类"><a href="#System类" class="headerlink" title="System类"></a>System类</h2><p>System类代表系统，系统级的很多属性和控制方法都放置在该类的内部。该类位于java.lang包。</p>
<ul>
<li><p>由于该类的构造器是private的，所以无法创建该类的对象，也就是无法实<br>例化该类。其内部的成员变量和成员方法都是static的，所以也可以很方便<br>的进行调用。</p>
</li>
<li><p>成员变量</p>
<ul>
<li>System类内部包含in、out和err三个成员变量，分别代表标准输入流<br>(键盘输入)，标准输出流(显示器)和标准错误输出流(显示器)。</li>
</ul>
</li>
<li><p>成员方法</p>
<ul>
<li><p><code>native long currentTimeMillis()</code>：<br>该方法的作用是返回当前的计算机时间，时间的表达格式为当前计算机时<br>间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。</p>
</li>
<li><p><code>void exit(int status)</code>：<br>该方法的作用是退出程序。其中status的值为0代表正常退出，非零代表<br>异常退出。使用该方法可以在图形界面编程中实现程序的退出功能等。</p>
</li>
<li><p><code>void gc()</code>：<br>该方法的作用是请求系统进行垃圾回收。至于系统是否立刻回收，则<br>取决于系统中垃圾回收算法的实现以及系统执行时的情况。</p>
</li>
<li><p><code>String getProperty(String key)</code>：<br>该方法的作用是获得系统中属性名为key的属性对应的值。系统中常见<br>的属性名以及属性的作用如下表所示：</p>
<p><img src="https://s2.loli.net/2023/02/07/cVQHo9jSmXAzDdt.png" alt="image-20230207154150702"></p>
</li>
</ul>
</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">String</span> javaVersion <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"java.version"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"java的version:"</span> <span class="token operator">+</span> javaVersion<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//java的version:1.8.0_181</span>

<span class="token class-name">String</span> javaHome <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"java.home"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"java的home:"</span> <span class="token operator">+</span> javaHome<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//java的home:C:\Program Files\Java\jdk1.8.0_181\jre</span>

<span class="token class-name">String</span> osName <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"os.name"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"os的name:"</span> <span class="token operator">+</span> osName<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//os的name:Windows 10</span>

<span class="token class-name">String</span> osVersion <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"os.version"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"os的version:"</span> <span class="token operator">+</span> osVersion<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//os的version:10.0</span>

<span class="token class-name">String</span> userName <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"user.name"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"user的name:"</span> <span class="token operator">+</span> userName<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//user的name:HengxingStu</span>

<span class="token class-name">String</span> userHome <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"user.home"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"user的home:"</span> <span class="token operator">+</span> userHome<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//user的home:C:\Users\HengxingStu</span>

<span class="token class-name">String</span> userDir <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">getProperty</span><span class="token punctuation">(</span><span class="token string">"user.dir"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"user的dir:"</span> <span class="token operator">+</span> userDir<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//user的dir:C:\Users\HengxingStu\Documents\CodeSpace\JavaSenior\day04</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Math类"><a href="#Math类" class="headerlink" title="Math类"></a>Math类</h2><p>java.lang.Math提供了一系列静态方法用于科学计算。其方法的参数和返回值类型一般为double型。</p>
<table>
<thead>
<tr>
<th align="center">abs</th>
<th align="center">绝对值</th>
</tr>
</thead>
<tbody><tr>
<td align="center">acos,asin,atan,cos,sin,tan</td>
<td align="center">三角函数</td>
</tr>
<tr>
<td align="center">sqrt</td>
<td align="center">平方根</td>
</tr>
<tr>
<td align="center">pow(double a,doble b)</td>
<td align="center">a的b次幂</td>
</tr>
<tr>
<td align="center">log</td>
<td align="center">自然对数</td>
</tr>
<tr>
<td align="center">exp</td>
<td align="center">e为底指数</td>
</tr>
<tr>
<td align="center">max(double a,double b)<br/>min(double a,double b)<br/>random()</td>
<td align="center">返回0.0到1.0的随机数</td>
</tr>
<tr>
<td align="center">long round(double a)</td>
<td align="center">double型数据a转换为long型（四舍五入）</td>
</tr>
<tr>
<td align="center">toDegrees(double angrad)</td>
<td align="center">弧度—&gt;角度</td>
</tr>
<tr>
<td align="center">toRadians(double angdeg)</td>
<td align="center">角度—&gt;弧度</td>
</tr>
</tbody></table>
<p>​    </p>
<h2 id="BigInteger类-和-BigDecimal类"><a href="#BigInteger类-和-BigDecimal类" class="headerlink" title="BigInteger类 和 BigDecimal类"></a>BigInteger类 和 BigDecimal类</h2><p>Integer类作为int的包装类，能存储的最大整型值为(2^31) -1，Long类也是有限的，最大为(2^63) -1。如果要表示再大的整数，不管是基本数据类型还是他们的包装类都无能为力，更不用说进行运算了。</p>
<ul>
<li><p><code>java.math</code>包的<code>BigInteger</code>可以表示不可变的任意精度的整数。BigInteger 提供<br>所有 Java 的基本整数操作符的对应物，并提供<code>java.lang.Math</code>的所有相关方法。<br>另外，BigInteger 还提供以下运算：模算术、GCD 计算、质数测试、素数生成、<br>位操作以及一些其他操作。</p>
</li>
<li><p>构造器</p>
<ul>
<li><code>BigInteger(String val)</code>：根据字符串构建<code>BigInteger</code>对象</li>
</ul>
</li>
<li><p>常用方法</p>
<ul>
<li><code>public BigInteger abs()</code>：返回此BigInteger的绝对值的BigInteger。</li>
<li><code>BigInteger add(BigInteger val)</code> ：返回其值为 (this + val) 的 BigInteger</li>
<li><code>BigInteger subtract(BigInteger val)</code>：返回其值为 (this - val) 的 BigInteger</li>
<li><code>BigInteger multiply(BigInteger val)</code>：返回其值为 (this * val) 的 BigInteger</li>
<li><code>BigInteger divide(BigInteger val)</code>：返回其值为 (this &#x2F; val) 的 BigInteger。整数相除只保留整数部分。</li>
<li><code>BigInteger remainder(BigInteger val)</code>：返回其值为 (this % val) 的 BigInteger。</li>
<li><code>BigInteger[] divideAndRemainder(BigInteger val)</code>：返回包含 (this &#x2F; val) 后跟(this % val) 的两个 BigInteger 的数组。</li>
<li><code>BigInteger pow(int exponent)</code>：返回其值为 (this exponent ) 的 BigInteger。</li>
</ul>
</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">hengxingstu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://hengxingstu.gitee.io/2023/02/03/code/Java%E5%B8%B8%E7%94%A8%E7%B1%BB/">https://hengxingstu.gitee.io/2023/02/03/code/Java%E5%B8%B8%E7%94%A8%E7%B1%BB/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://hengxingstu.gitee.io" target="_blank">恒星同学</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="https://s2.loli.net/2023/02/03/uwhRQAO6rqZgWVi.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/02/07/code/Java%E6%9E%9A%E4%B8%BE%E7%B1%BB%E4%B8%8E%E6%B3%A8%E8%A7%A3/"><img class="prev-cover" src="https://s2.loli.net/2023/02/08/PQEkKusxfo9HqCe.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java高级-枚举类与注解</div></div></a></div><div class="next-post pull-right"><a href="/2023/01/30/code/JavaThread/"><img class="next-cover" src="https://s2.loli.net/2023/01/31/TyPcrql46CJWB8D.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java高级-多线程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/01/26/code/JavaException/" title="Java的异常处理"><img class="cover" src="https://s2.loli.net/2023/01/26/TG4D6pZl3wYQ8by.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-26</div><div class="title">Java的异常处理</div></div></a></div><div><a href="/2023/01/30/code/JavaThread/" title="Java高级-多线程"><img class="cover" src="https://s2.loli.net/2023/01/31/TyPcrql46CJWB8D.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-30</div><div class="title">Java高级-多线程</div></div></a></div><div><a href="/2023/01/08/code/Java%E6%95%B0%E7%BB%84/" title="数组的复制、反转、查找、排序"><img class="cover" src="https://api.vvhan.com/api/view" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-08</div><div class="title">数组的复制、反转、查找、排序</div></div></a></div><div><a href="/2023/02/07/code/Java%E6%9E%9A%E4%B8%BE%E7%B1%BB%E4%B8%8E%E6%B3%A8%E8%A7%A3/" title="Java高级-枚举类与注解"><img class="cover" src="https://s2.loli.net/2023/02/08/PQEkKusxfo9HqCe.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-07</div><div class="title">Java高级-枚举类与注解</div></div></a></div><div><a href="/2023/02/08/code/Java%E9%9B%86%E5%90%88(%E4%B8%8A)/" title="Java高级-集合-Collection部分"><img class="cover" src="https://cdn.jsdelivr.net/gh/hengxingstu/Blog-img/mc/00f3e6da1f364172c08d6dc6ddb4a077e.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-08</div><div class="title">Java高级-集合-Collection部分</div></div></a></div><div><a href="/2023/02/10/code/Java%E9%9B%86%E5%90%88(%E4%B8%8B)/" title="Java高级-集合-Map部分"><img class="cover" src="https://cdn.jsdelivr.net/gh/hengxingstu/Blog-img/mc/00f3e6da1f364172c08d6dc6ddb4a077e.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-10</div><div class="title">Java高级-集合-Map部分</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://wallpapercave.com/uwp/uwp2365506.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">hengxingstu</div><div class="author-info__description"></div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">36</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">23</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">8</div></a></div></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/hengxingstu"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/hengxingstu" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:hengxingstu@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的博客，欢迎和我联系，交流是最好的老师</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#String%E7%B1%BB"><span class="toc-number">1.</span> <span class="toc-text">String类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%8B%BC%E6%8E%A5"><span class="toc-number">1.1.</span> <span class="toc-text">字符串拼接</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%A2%E8%AF%95%E9%A2%98"><span class="toc-number">1.1.1.</span> <span class="toc-text">面试题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F"><span class="toc-number">1.1.2.</span> <span class="toc-text">注意</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">1.2.</span> <span class="toc-text">常用方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#String-%E4%B8%8E%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E3%80%81%E5%8C%85%E8%A3%85%E7%B1%BB%E4%B9%8B%E9%97%B4%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="toc-number">1.3.</span> <span class="toc-text">String 与基本数据类型、包装类之间的转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#String-%E4%B8%8E-char-%E4%B9%8B%E9%97%B4%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="toc-number">1.4.</span> <span class="toc-text">String 与 char[]之间的转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#String-%E4%B8%8E-byte-%E4%B9%8B%E9%97%B4%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="toc-number">1.5.</span> <span class="toc-text">String 与 byte[]之间的转换</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%83%E4%B9%A0%E9%A2%98"><span class="toc-number">1.6.</span> <span class="toc-text">练习题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E6%8B%9F%E4%B8%80%E4%B8%AAtrim%E6%96%B9%E6%B3%95%EF%BC%8C%E5%8E%BB%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%A4%E7%AB%AF%E7%9A%84%E7%A9%BA%E6%A0%BC%E3%80%82"><span class="toc-number">1.6.1.</span> <span class="toc-text">模拟一个trim方法，去除字符串两端的空格。</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%86%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%BF%9B%E8%A1%8C%E5%8F%8D%E8%BD%AC%E3%80%82%E5%B0%86%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E6%8C%87%E5%AE%9A%E9%83%A8%E5%88%86%E8%BF%9B%E8%A1%8C%E5%8F%8D%E8%BD%AC%E3%80%82"><span class="toc-number">1.6.2.</span> <span class="toc-text">将一个字符串进行反转。将字符串中指定部分进行反转。</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%9C%A8%E5%8F%A6%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E5%87%BA%E7%8E%B0%E7%9A%84%E6%AC%A1%E6%95%B0%E3%80%82"><span class="toc-number">1.6.3.</span> <span class="toc-text">获取一个字符串在另一个字符串中出现的次数。</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96%E4%B8%A4%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E6%9C%80%E5%A4%A7%E7%9B%B8%E5%90%8C%E5%AD%90%E4%B8%B2%E3%80%82"><span class="toc-number">1.6.4.</span> <span class="toc-text">获取两个字符串中最大相同子串。</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E5%AD%97%E7%AC%A6%E8%BF%9B%E8%A1%8C%E8%87%AA%E7%84%B6%E9%A1%BA%E5%BA%8F%E6%8E%92%E5%BA%8F%E3%80%82"><span class="toc-number">1.6.5.</span> <span class="toc-text">对字符串中字符进行自然顺序排序。</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#StringBuffer%E3%80%81StringBuilder%E7%B1%BB"><span class="toc-number">2.</span> <span class="toc-text">StringBuffer、StringBuilder类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8EString%E6%AF%94%E8%BE%83"><span class="toc-number">2.0.1.</span> <span class="toc-text">与String比较</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">2.0.2.</span> <span class="toc-text">其常用方法</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Date%E7%B1%BB"><span class="toc-number">3.</span> <span class="toc-text">Date类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#System%E7%B1%BB%E6%97%B6%E9%97%B4"><span class="toc-number">3.1.</span> <span class="toc-text">System类时间</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JDK-8%E4%B9%8B%E5%89%8D%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4%E7%9A%84API"><span class="toc-number">3.2.</span> <span class="toc-text">JDK 8之前日期和时间的API</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#java-util-Date%E7%B1%BB%E5%8F%8A%E5%85%B6%E5%AD%90%E7%B1%BB"><span class="toc-number">3.2.1.</span> <span class="toc-text">java.util.Date类及其子类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#SimpleDateFormat%E7%B1%BB"><span class="toc-number">3.2.2.</span> <span class="toc-text">SimpleDateFormat类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Calendar%E7%B1%BB"><span class="toc-number">3.2.3.</span> <span class="toc-text">Calendar类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JDK-8%E4%B8%AD%E6%96%B0%E7%9A%84%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4API"><span class="toc-number">3.3.</span> <span class="toc-text">JDK 8中新的日期和时间API</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#java-time"><span class="toc-number">3.3.1.</span> <span class="toc-text">java.time</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9E%AC%E6%97%B6%EF%BC%9AInstant"><span class="toc-number">3.3.2.</span> <span class="toc-text">瞬时：Instant</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DateTimeFormatter%E7%B1%BB"><span class="toc-number">3.3.3.</span> <span class="toc-text">DateTimeFormatter类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E5%AE%83API"><span class="toc-number">3.3.4.</span> <span class="toc-text">其它API</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%82%E8%80%83%EF%BC%9A%E4%B8%8E%E4%BC%A0%E7%BB%9F%E6%97%A5%E6%9C%9F%E5%A4%84%E7%90%86%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="toc-number">3.3.4.1.</span> <span class="toc-text">参考：与传统日期处理的转换</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%AF%94%E8%BE%83%E7%B1%BB"><span class="toc-number">4.</span> <span class="toc-text">比较类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Comparable%E6%8E%A5%E5%8F%A3-%E8%87%AA%E7%84%B6%E6%8E%92%E5%BA%8F"><span class="toc-number">4.1.</span> <span class="toc-text">Comparable接口-自然排序</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E4%BA%8EString%E7%B1%BB%E3%80%81%E5%8C%85%E8%A3%85%E7%B1%BB"><span class="toc-number">4.1.1.</span> <span class="toc-text">对于String类、包装类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E4%BA%8E%E8%87%AA%E5%AE%9A%E4%B9%89%E7%B1%BB"><span class="toc-number">4.1.2.</span> <span class="toc-text">对于自定义类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Comparator%E6%8E%A5%E5%8F%A3-%E5%AE%9A%E5%88%B6%E6%8E%92%E5%BA%8F"><span class="toc-number">4.2.</span> <span class="toc-text">Comparator接口-定制排序</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Comparable%E6%8E%A5%E5%8F%A3%E4%B8%8EComparator%E7%9A%84%E4%BD%BF%E7%94%A8%E7%9A%84%E5%AF%B9%E6%AF%94"><span class="toc-number">4.3.</span> <span class="toc-text">Comparable接口与Comparator的使用的对比</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E7%B1%BB"><span class="toc-number">5.</span> <span class="toc-text">其他类</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#System%E7%B1%BB"><span class="toc-number">5.1.</span> <span class="toc-text">System类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Math%E7%B1%BB"><span class="toc-number">5.2.</span> <span class="toc-text">Math类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#BigInteger%E7%B1%BB-%E5%92%8C-BigDecimal%E7%B1%BB"><span class="toc-number">5.3.</span> <span class="toc-text">BigInteger类 和 BigDecimal类</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/02/21/code/springMVC%E6%96%87%E6%A1%A3/" title="Spring参考文档"><img src="https://s2.loli.net/2023/02/21/vdVhPU5RITfrXg4.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring参考文档"/></a><div class="content"><a class="title" href="/2023/02/21/code/springMVC%E6%96%87%E6%A1%A3/" title="Spring参考文档">Spring参考文档</a><time datetime="2023-02-21T12:26:00.000Z" title="发表于 2023-02-21 20:26:00">2023-02-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/16/code/SpringMVC%E7%AC%94%E8%AE%B0/" title="SpringMVC学习笔记"><img src="https://s2.loli.net/2023/02/16/N8E1LGTUnYVdmPk.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="SpringMVC学习笔记"/></a><div class="content"><a class="title" href="/2023/02/16/code/SpringMVC%E7%AC%94%E8%AE%B0/" title="SpringMVC学习笔记">SpringMVC学习笔记</a><time datetime="2023-02-16T09:06:00.000Z" title="发表于 2023-02-16 17:06:00">2023-02-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/16/code/Spring%E4%BA%8B%E5%8A%A1/" title="Spring学习笔记"><img src="https://s2.loli.net/2023/02/16/N8E1LGTUnYVdmPk.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习笔记"/></a><div class="content"><a class="title" href="/2023/02/16/code/Spring%E4%BA%8B%E5%8A%A1/" title="Spring学习笔记">Spring学习笔记</a><time datetime="2023-02-16T09:06:00.000Z" title="发表于 2023-02-16 17:06:00">2023-02-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/15/code/SpringAop%E7%AC%94%E8%AE%B0/" title="SpringAOP笔记"><img src="https://s2.loli.net/2023/02/08/jWNelFA4c7BGkTw.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="SpringAOP笔记"/></a><div class="content"><a class="title" href="/2023/02/15/code/SpringAop%E7%AC%94%E8%AE%B0/" title="SpringAOP笔记">SpringAOP笔记</a><time datetime="2023-02-15T13:00:00.000Z" title="发表于 2023-02-15 21:00:00">2023-02-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/12/code/Spring%E7%AC%94%E8%AE%B0/" title="Spring学习笔记"><img src="https://s2.loli.net/2023/02/12/ukqiYOMfcU4WwCJ.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习笔记"/></a><div class="content"><a class="title" href="/2023/02/12/code/Spring%E7%AC%94%E8%AE%B0/" title="Spring学习笔记">Spring学习笔记</a><time datetime="2023-02-12T05:58:00.000Z" title="发表于 2023-02-12 13:58:00">2023-02-12</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By hengxingstu</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo-hengxing.vercel.app/',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.vemoji)'))
      }
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'https://twikoo-hengxing.vercel.app/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      document.getElementById('twikoo-count').innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    GLOBAL_CONFIG_SITE.isPost && getCount()
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !false) {
    if (false) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.618,"jsonPath":"/live2dw/assets/haru02.model.json"},"display":{"superSample":2,"width":200,"height":400,"position":"right","hOffset":10,"vOffset":0},"mobile":{"show":false,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.2},"dialog":{"enable":true,"hitokoto":true},"log":false});</script></body></html>